package org.gh.blackcloud;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceHandler {
	
	private RemoteStore remoteStore;
	
	public ReplaceHandler(RemoteStore remoteStore) {
		this.remoteStore = remoteStore;
	}
	
	/**
	 * 替换html中本地文件为远端文件
	 * @param html
	 * @return
	 */
	public String replaceHtmlLocal2Remote(String html, String requestUrl) {
		StringBuilder builder = new StringBuilder(html);
		Pattern p = Pattern.compile("<img [^>]*src=\"([^ ]+)\"[^>]*>");		
		Matcher m = p.matcher(html);
		int i = 0;
		while (m.find(i)) {
			i = m.end();
			String imgStr = m.group();
			String imgUrl = m.group(1);
			String remoteImgUrl = null;
			if ((remoteImgUrl = remoteStore.get(imgUrl)) == null) {
				continue;
			}
			String repalceImg = imgStr.replaceFirst(imgUrl, remoteImgUrl);
			int start = builder.indexOf(imgStr);
			int end = start + imgStr.length();
			builder.replace(start, end, repalceImg);
		}
		return builder.toString();
	}
}
